using UnityEngine;
using System.Collections;

public class Pause : MonoBehaviour {
	
	public GameObject pause;
	public MonoBehaviour[] exceptions;
	private PauseManager pauseManager;
	public AudioSource audioPause;
	private bool isPause = true;
	private bool ready;
	private CharacterManager characterManager;
	private DataManager data;
	
	IEnumerator Start()
	{
		characterManager = GameObject.FindGameObjectWithTag("Player").GetComponent<CharacterManager>();
		pauseManager = pause.GetComponent<PauseManager>();
		yield return new WaitForSeconds(0.3f);	
		audioPause = GameObject.Find("AudioBehavior").GetComponent<AudioSource>();

        data = GameObject.FindGameObjectWithTag("_Manager").GetComponent<DataManager>();

		ready = true;
	}
	
	void Update () 
	{
		if(Input.GetButtonDown("Fire1") && ready)
		{
			if(isPause && !GameObject.FindGameObjectWithTag("Achievement"))
			{
				EnterPause();
			}	
			
		}
	}
	
	public void EnterPause()
	{
		characterManager.rigidbody.velocity = new Vector3(0,0,0);

		Object[] obj = FindObjectsOfType(typeof(MonoBehaviour));
		
		foreach(Object currentObj in obj)
		{
			MonoBehaviour currentScript = (MonoBehaviour) currentObj;
			if(currentScript.name != "PauseManager")
			{
				currentScript.enabled = false;
				currentScript.StopAllCoroutines();
			}
		}
		
		characterManager.DeactiveAll();
		audioPause.Pause();
		
		isPause = false;
		pause.SetActive(true);
		#if UNITY_STANDALONE_WIN || UNITY_WEBPLAYER

		pauseManager.ActiveElement();
		#endif
		
		if(!Application.loadedLevelName.Equals("Tutorial"))
		data.enabled = false;
}
	
	public void Return()
	{
		
		Object[] obj = FindObjectsOfType(typeof(MonoBehaviour));
		
		foreach(Object currentObj in obj)
		{
			MonoBehaviour currentScript = (MonoBehaviour) currentObj;
			currentScript.enabled = true;
			currentScript.gameObject.SendMessage("OnResume",SendMessageOptions.DontRequireReceiver);
		}
		
		if(characterManager)
		characterManager.reactiveAll();
		audioPause.Play();
		
		#if UNITY_IPHONE || UNITY_ANDROID

		//GameObject.Find("Retomar").renderer.material.color = Color.black;
		
		#endif
		
		pause.SetActive(false);
		isPause = true;
		
		if(!Application.loadedLevelName.Equals("Tutorial"))
		data.enabled = true;
	}
	
	
}
